package cn.skcks.controller;

import cn.skcks.pojo.Books;
import cn.skcks.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.print.Book;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
	// controller 调用 service 层
	private BookService bookService;

	@Autowired
	@Qualifier("bookServiceImpl")
	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}

	// 查询所有书籍 并返回
	@RequestMapping("/all")
	public String allBook(Model model) {
		List<Books> list = bookService.allBook();

		System.out.println(list);
		model.addAttribute("list", list);

		return "showBooks";
	}

	// 添加数据 并 重定向 到 查看所有书籍页面
	@RequestMapping(value = "/addBook",method = RequestMethod.POST)
	public String addBook(@RequestParam("name") String name, @RequestParam("num") int num, @RequestParam("detail") String detail) {

		Books book = new Books(-1, name, num, detail);

		bookService.addBook(book);

		return "redirect:/book/all";
	}

	// 跳转到添加书籍页面
	@RequestMapping("/toAddBook")
	public String toAddBook() {
		return "addBook";
	}

	@RequestMapping(value = "/modBook",method = RequestMethod.POST)
	public String modBook(Books book){
		System.out.println(book);
		bookService.modBook(book);
		return "redirect:/book/all";
	}

	// 跳转到修改书籍页面
	@RequestMapping("/toModBook")
	public String toModBook(Model model,int id){
		Books book = bookService.getBookById(id);

		model.addAttribute("book",book);

		return "modBook";
	}

	@RequestMapping("/delBook")
	public String delBook(int id){
		bookService.delBook(id);
		return "redirect:/book/all";
	}

	@RequestMapping("getBookByName")
	public String getBookByName(Model model,String bookName){
		model.addAttribute("list",bookService.getBookByName(bookName));
		return "showBooks";
	}
}